// ---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "HttpThread.h"
#pragma package(smart_init)
// ---------------------------------------------------------------------------

// Important: Methods and properties of objects in VCL can only be
// used in a method called using Synchronize, for example:
//
// Synchronize(&UpdateCaption);
//
// where UpdateCaption could look like:
//
// void __fastcall THttpThread::UpdateCaption()
// {
// Form1->Caption = "Updated in a thread";
// }
// ---------------------------------------------------------------------------

__fastcall THttpThread::THttpThread(HashTable list, String dir) : TThread
(false) {
	this->list = list;
	SetCurrentDirectory(dir.t_str());
}

// ---------------------------------------------------------------------------
void __fastcall THttpThread::Execute() {
	stream = new TMemoryStream();
	FreeOnTerminate = true;
	http = new TIdHTTP(NULL);
	http->ProtocolVersion = pv1_1;
	http->Request->Username = "admin";
	http->Request->Password = "godlike";
	http->Request->CacheControl = "no-cache";
	http->Request->Accept = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
	try {
		http->OnStatus = UMainForm->httpStatus;
		http->OnWork = UMainForm->httpWork;
		http->OnWorkBegin = UMainForm->httpWorkBegin;
		http->OnWorkEnd = UMainForm->httpWorkEnd;
		String name;
		map<String, String>::iterator it;
		for (it = list.begin(); it != list.end(); it++) {
			stream->Clear();
			name = it->first;
			http->Get(name, stream);
			if (FileExists(it->second))
				DeleteFile(it->second);
			stream->SaveToFile(it->second);
		}
		Synchronize(&UpdateComplete);
	}
	__finally {
		delete http;
		delete stream;
	}
}
// ---------------------------------------------------------------------------
void __fastcall THttpThread::UpdateComplete(){
	UMainForm->UpdateComplete();
}
// ---------------------------------------------------------------------------
